'use client';

import type { IPostTemplate } from '@/interfaces';
import { useQuery } from '@tanstack/react-query';
import { queryPostTemplateBySection } from '@/services/api';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import classNames from 'classnames';
import { useState } from 'react';
import useToast from '@/hooks/useToast';
import type { TMetadata } from '@/types';
import { useTranslations } from 'use-intl';

export default function PostTemplate(
  this: any,
  {
    sectionId,
    metadata,
    hideModal,
    setData,
  }: {
    sectionId: number;
    metadata: TMetadata;
    hideModal: () => void;
    setData: (value: any) => void;
  },
) {
  const [currentItem, setCurrentItem] = useState<IPostTemplate>();
  const { show } = useToast();
  const t = useTranslations('PostEditPage');

  const queryPostTemplateBySectionQuery = useQuery(
    ['/forum', '/templates', '/sections', sectionId],
    async (context) => {
      return (await queryPostTemplateBySection({
        id: context.queryKey[3],
      })) as IPostTemplate[];
    },
    {
      keepPreviousData: true,
    },
  );

  function onClickItem(item: IPostTemplate) {
    setCurrentItem(item);
  }

  function onClickApply() {
    try {
      if (!currentItem) {
        show({
          type: 'DANGER',
          message: t('noPostTemplateSelected'),
        });
        return;
      }

      const content = currentItem.content;
      if (!content) {
        show({
          type: 'DANGER',
          message: t('currentPostTemplateHasNoContent'),
        });
        return;
      }

      setData(content);

      show({
        type: 'SUCCESS',
        message: t('applicationCompleted'),
      });
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  if (queryPostTemplateBySectionQuery.data) {
    const data = queryPostTemplateBySectionQuery.data;

    return (
      <div className="row">
        <div className="col">
          {data.length > 0 && (
            <div className="vstack gap-4">
              <div>
                <mark>
                  <i className="bi bi-info-circle"></i>
                </mark>
                <ol className="text-muted">
                  <li>
                    {t('clickingPostTemplateWillApplyContentToEditorDirectly')}
                  </li>
                  <li>
                    {t('ifContentInEditorIsImportantPleaseCopyToClipboard')}
                  </li>
                </ol>
              </div>

              <div className="row g-4">
                <div className="col">
                  <div className="list-group">
                    {data.map((item) => {
                      return (
                        <button
                          onClick={onClickItem.bind(this, item)}
                          key={item.id}
                          type="button"
                          className={classNames(
                            'list-group-item list-group-item-action',
                            currentItem && currentItem.id === item.id
                              ? 'active'
                              : false,
                          )}
                          aria-current="true"
                        >
                          {item.name}
                        </button>
                      );
                    })}
                  </div>
                </div>
                {currentItem && (
                  <div className="col-12">
                    <div className="card">
                      <div className="card-header">
                        <div className="d-flex align-items-center justify-content-between">
                          <button
                            onClick={onClickApply}
                            type="button"
                            className="btn btn-secondary"
                          >
                            {t('applyTemplate')}
                          </button>
                        </div>
                      </div>
                      <div className="card-body">
                        <div className="vstack gap-4">
                          {currentItem.overview && (
                            <>
                              <div>{currentItem.overview}</div>
                              <hr />
                            </>
                          )}

                          <div
                            className="clearfix text-break content-layer"
                            dangerouslySetInnerHTML={{
                              __html: currentItem.content,
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div></div>
            </div>
          )}

          {data.length === 0 && (
            <Alert message={t('noTemplateAvailableToApply')} />
          )}
        </div>
      </div>
    );
  }

  if (queryPostTemplateBySectionQuery.error) {
    return (
      <Alert type="error" message={queryPostTemplateBySectionQuery.error} />
    );
  }

  return <AlertLoad />;
}
